package com.kate.mall.order.price;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kate.mall.order.dto.OrderItemDTO;
import com.kate.mall.order.dto.PromotionActivityDTO;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;


/**
 * @Description: 满减类型的促销活动价格计算组件
 * @Auther: 新梦想*陈超
 * @Date: 2021/10/30 19:34
 */
@Component
public class ReachDiscountPromotionActivityCalculator implements PromotionActivityCalculator {


	/**
	 * 计算促销活动的减免金额
	 */
	@Override
	public PromotionActivityResult calculate(OrderItemDTO item,
											 PromotionActivityDTO promotionActivity) throws Exception {
		BigDecimal totalAmount =  item.getPrice().multiply(new BigDecimal(item.getNumber()));

		String rulesJson = promotionActivity.getRule();
		
		JSONArray rules = JSONUtil.parseArray(rulesJson);
		
		for(int i = 0; i < rules.size(); i++) {
			JSONObject rule = rules.getJSONObject(i);

			BigDecimal thresholdAmount = rule.get("thresholdAmount", BigDecimal.class);

			BigDecimal reduceAmount = rule.get("reduceAmount", BigDecimal.class);
			//Double thresholdAmount = jsonExtractor.getDouble(rule, "thresholdAmount");
			//Double reduceAmount = jsonExtractor.getDouble(rule, "reduceAmount");
			
			if(totalAmount.compareTo(reduceAmount)>1) {
				return new PromotionActivityResult(reduceAmount); 
			}
		}
		
		return new PromotionActivityResult(); 
	}

}
